<template>
    <div class="goods-info-wrap flex">
        <template v-if="goodsInfo.spec_type == 20">
            <div class="goods-img" v-if='selectShop.image'>
                <base-img :src="selectShop.image" mode="contain"></base-img>
            </div>
            <div class="goods-img" v-else>
                <div class="swiper-container" id='goodsDetailSwiper' v-if="goodsInfo[goodsThumbName].length > 0">
                    <div class="swiper-wrapper">
                        <div class="swiper-slide" v-for="(item, index) in goodsInfo[goodsThumbName]" :key="index">
                            <div class="swiper-img">
                                <base-img :src="item" mode="contain"></base-img>
                            </div>
                        </div>
                    </div>
                </div>
                <base-img :src="goodsInfo[goodsThumbName][0]" mode="contain" v-else></base-img>
            </div>
        </template>
        <template v-else>
            <div class="goods-img">
                <div class="swiper-container" id='goodsDetailSwiper' v-if="goodsInfo[goodsThumbName].length > 0">
                    <div class="swiper-wrapper">
                        <div class="swiper-slide" v-for="(item, index) in goodsInfo[goodsThumbName]" :key="index">
                            <div class="swiper-img">
                                <base-img :src="item" mode="contain"></base-img>
                            </div>
                        </div>
                    </div>
                </div>
                <base-img :src="goodsInfo[goodsThumbName][0]" mode="contain" v-else></base-img>
            </div>
        </template>
        <div class="right-goods-info">
            <p>{{ goodsInfo.name }}</p>
            <h4>{{ minBuyNumCom }}件起购</h4>
            <div class="goods-price-wrap">
                <h2>平台价</h2>
                <div class="goods-price flex">
                    <p><i>￥</i>{{ selectShop.price ?  selectShop.price:goodsInfo['goods_price']}}<i class="unit" v-if="goodsInfo.goods_unit">/{{ selectShop.unit ? selectShop.unit : goodsInfo.goods_unit}}</i></p>
                    <span class="flex-center">销售价：¥ {{selectShop.market_price ? selectShop.market_price : goodsInfo['market_price']}}<i v-if="goodsInfo.goods_unit" style="font-size: 10px;">/{{ selectShop.unit ? selectShop.unit : goodsInfo.goods_unit}}</i></span>
                </div>
            </div>
            <!-- 商品规格 -->
            <div class="attr-info-wrap">
                <div class="attr-item" v-for="(item, index1) in goodsInfo[specListName]" :key="index1">
                    <h3 class="attr-name">{{ item.name }}：</h3>
                    <div class="attr">
                        <button class="attr-btn" :class="[
                                item_value.ishow ? '' : 'noactived',
                                subIndex[index1] == index2 ? 'actived' : '',
                            ]" v-for="(item_value, index2) in item.list" :key="index2" @click="skuClick(item_value, index1, index2)">
                            {{ item_value.name }}
                        </button>
                    </div>
                </div>
            </div>
            <!-- 产地 -->
            <div class="producer-wrap flex">
                <h3 class="attr-name">产地：</h3>
                <p class="producer">{{ goodsInfo.producer }}</p>
            </div>
            <!-- 选择商品数量 -->
            <div class="number-box-wrap flex">
                <h3 class="attr-name">数量：</h3>
                <number-box v-model="selectNum" :min="minBuyNumCom || 1" :max="maxBuyNumCom" :step="stepBuyNum || 1" :step-strictly="stepStrictly"
                            :positive-integer="true" :selectShop='selectShop'>
                </number-box>
                <p class="stock">库存：{{ stockCom }}</p>
            </div>
            <!-- 商品加购操作 -->
            <div class="goods-handle-wrap flex" v-if="outFoStock">
                <button class="add-cart add-cart-disabled">{{ noStockText }}</button>
                <div class="line"></div>
                <div class="collect flex-center" @click='toCollect'>
                    <span class="iconfont icon-31shoucangxuanzhong check" v-if='goodsInfo.collect_flag == 1'></span>
                    <span class="iconfont icon-shoucang" v-else></span>
                    <p :class="[goodsInfo.collect_flag == 1 ? 'check':'']">收藏</p>
                </div>
            </div>
            <div class="goods-handle-wrap flex" v-else>
                <button class="add-cart" @click="addCart()" v-if='!isAddBtnDisabled'>{{ addCartBtnText }}</button>
                <button class="add-cart add-cart-disabled" v-else>{{ addCartBtnText }}</button>
                <div class="line"></div>
                <div class="collect flex-center" @click='toCollect'>
                    <span class="iconfont icon-31shoucangxuanzhong check" v-if='goodsInfo.collect_flag == 1'></span>
                    <span class="iconfont icon-shoucang" v-else></span>
                    <p :class="[goodsInfo.collect_flag == 1 ? 'check':'']">收藏</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import "swiper/css/swiper.css";
import Swiper from "swiper";
import NumberBox from './number-box'
var vk; // vk依赖
var goodsCache = {}; // 本地商品缓存
import {
    saveUserCollect
} from '../api/goods'
export default {
    name: "GoodsSku",
    components: {
        NumberBox
    },
    props: {
        // vk云函数路由模式参数开始-----------------------------------------------------------
        // 商品id
        goodsId: {
            Type: String,
            default: ""
        },
        // vk路由模式框架下的云函数地址
        action: {
            Type: String,
            default: ""
        },
        // vk云函数路由模式参数结束-----------------------------------------------------------
        // 该商品已抢完时的按钮文字
        noStockText: {
            Type: String,
            default: "该商品已抢完"
        },
        // 库存文字
        stockText: {
            Type: String,
            default: "库存"
        },
        // 商品表id的字段名
        goodsIdName: {
            Type: String,
            default: "_id"
        },
        // sku表id的字段名
        skuIdName: {
            Type: String,
            default: "_id"
        },
        // sku_list的字段名
        skuListName: {
            Type: String,
            default: "sku_list"
        },
        // spec_list的字段名
        specListName: {
            Type: String,
            default: "spec_list"
        },
        // 库存的字段名 默认 stock
        stockName: {
            Type: String,
            default: "stock"
        },
        // sku组合路径的字段名
        skuArrName: {
            Type: String,
            default: "sku_name_arr"
        },
        // 默认单规格时的规格组名称
        defaultSingleSkuName: {
            Type: String,
            default: "默认"
        },
        // 模式 1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1
        mode: {
            Type: Number,
            default: 1
        },
        // 点击遮罩是否关闭组件 true 关闭 false 不关闭 默认true
        maskCloseAble: {
            Type: Boolean,
            default: true
        },
        // 顶部圆角值
        borderRadius: {
            Type: [String, Number],
            default: 0
        },
        // 商品缩略图字段名(未选择sku时)
        goodsThumbName: {
            Type: [String],
            default: "goods_thumb"
        },
        // 商品缩略图背景颜色，如#999999
        goodsThumbBackgroundColor: {
            Type: String,
            default: "#F2F4F7"
        },
        // 最小购买数量 默认 1
        minBuyNum: {
            Type: [Number, String],
            default: 1
        },
        // 最大购买数量 默认 100000
        maxBuyNum: {
            Type: [Number, String],
            default: 100000
        },
        // 步进器步长 默认 1
        stepBuyNum: {
            Type: [Number, String],
            default: 1
        },
        // 是否只能输入 step 的倍数
        stepStrictly: {
            Type: Boolean,
            default: false
        },
        // 自定义获取商品信息的函数,支付宝小程序不支持该属性,请使用localdata属性
        customAction: {
            Type: [Function],
            default: null
        },
        // 本地数据源
        localdata: {
            type: Object
        },
        // 价格的字体颜色
        priceColor: {
            Type: String
        },
        // 立即购买按钮的文字
        buyNowText: {
            Type: String,
            default: "立即购买"
        },
        // 立即购买按钮的字体颜色
        buyNowColor: {
            Type: String
        },
        // 立即购买按钮的背景颜色
        buyNowBackgroundColor: {
            Type: String
        },
        // 加入购物车按钮的文字
        addCartText: {
            Type: String,
            default: "加入购物车"
        },
        // 加入购物车按钮的字体颜色
        addCartColor: {
            Type: String
        },
        // 加入购物车按钮的背景颜色
        addCartBackgroundColor: {
            Type: String
        },
        // 不可点击时,按钮的样式
        disableStyle: {
            Type: Object,
            default: null
        },
        // 按钮点击时的样式
        activedStyle: {
            Type: Object,
            default: null
        },
        // 按钮常态的样式
        btnStyle: {
            Type: Object,
            default: null
        },
        // 是否显示右上角关闭按钮
        showClose: {
            Type: Boolean,
            default: true
        },
        // 关闭按钮的图片地址 https://img.alicdn.com/imgextra/i1/121022687/O1CN01ImN0O11VigqwzpLiK_!!121022687.png
        closeImage: {
            Type: String,
            default: ""
        },
        // 是否隐藏库存显示
        hideStock: {
            Type: Boolean,
            default: false
        },
        // 颜色主题
        theme: {
            Type: String,
            default: "default"
        },
        // 请求中的提示
        actionTips: {
            Type: String,
            default: "请求中..."
        },
        // 默认选中的SKU
        defaultSelect: {
            Type: Object
        },
        // 是否使用缓存
        useCache: {
            Type: Boolean,
            default: true
        },
        /**
         * 默认商品,设置该值可快速展示商品
         * 逻辑: 先展示 defaultGoods 信息,再取数据库,再更新页面(通常为更新库存)
         */
        defaultGoods: {
            Type: Object
        },
        /**
         * 金额是否需要除以100
         * 1:金额会除以100
         * 0:金额不会除以100
         */
        amountType: {
            Type: Number,
            default: 1
        },
        // 每次选择完SKU后，购买数量归1，如果有最小购买数量，则设置为最小购买数量
        selectedInit: {
            Type: Boolean,
            default: false
        },
    },
    data() {
        return {
            complete: false, // 组件是否加载完成
            goodsInfo: {}, // 商品信息
            isShow: false, // true 显示 false 隐藏
            initKey: true, // 是否已初始化
            shopItemInfo: {}, // 存放要和选中的值进行匹配的数据
            selectArr: [], // 存放被选中的值
            subIndex: [], // 是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
            selectShop: {}, // 存放最后选中的商品
            selectNum: this.minBuyNum || 1, // 选中数量
            outFoStock: false, // 是否全部sku都缺货
            openTime: 0,
            isAddBtnDisabled: false,//检查 规格 库存数量是否小于最低购买数量，如果小于，则让加入购物车按钮不可点击
            addCartBtnText: this.addCartText
        };
    },
    // 监听
    watch: {
        defaultGoods: {
            immediate: true,
            handler: function (newVal, oldValue) {
                let that = this;
                let { goodsIdName } = that;
                if (
                    typeof newVal === "object" &&
                    newVal &&
                    newVal[goodsIdName] &&
                    !goodsCache[newVal[goodsIdName]]
                ) {
                    that.pushGoodsCache(newVal);
                }
            },
        },
        localdata: {
            immediate: true,
            handler: function (newVal, oldValue) {
                let that = this;
                console.log('localdata', that.localdata)
                that.localdata = newVal;
                that.open();
                that.initSwiper();
                console.log('selectShop === ', that.selectShop)
            },
        },
    },
    created() {

    },
    methods: {
        //初始化swiper
        initSwiper() {
            setTimeout(() => {
                var goodsSwiper = new Swiper("#goodsDetailSwiper", {
                    autoplay: true,
                    loop: true,
                });
            }, 100)
        },
        //收藏
        toCollect() {
            const that = this;
            saveUserCollect({
                goods_id: that.goodsInfo._id
            }).then(res => {
                if (res.code == 0) {
                    that.goodsInfo.collect_flag = that.goodsInfo.collect_flag == 0 ? 1 : 0;
                    that.$message.success(res.msg)
                }
            })
        },
        // 初始化
        init(notAutoClick) {
            let that = this;
            // 清空之前的数据
            that.selectArr = [];
            that.subIndex = [];
            that.selectShop = {};
            that.selectNum = that.minBuyNum || 1;
            that.outFoStock = false;
            that.shopItemInfo = {};
            let specListName = that.specListName;
            that.goodsInfo[specListName].map(item => {
                that.selectArr.push("");
                that.subIndex.push(-1);
            });
            console.log('that.goodsInfo',that.goodsInfo)
            that.checkItem(); // 计算sku里面规格形成路径
            that.checkInpath(-1); // 传-1是为了不跳过循环
            if (!notAutoClick) that.autoClickSku(); // 自动选择sku策略
        },
        getValue() {
            // #ifndef VUE3
            return this.value;
            // #endif

            // #ifdef VUE3
            return this.modelValue;
            // #endif
        },
        // 使用vk路由模式框架获取商品信息
        findGoodsInfo(obj = {}) {
            let that = this;
            let {
                useCache
            } = obj;
            if (typeof vk == "undefined") {
                that.$message.error("custom-action必须是function")
                return false;
            }
            let {
                actionTips
            } = that;
            let actionTitle = "";
            let actionAoading = false;
            if (actionTips !== "custom") {
                actionTitle = useCache ? "" : "请求中...";
            } else {
                actionAoading = useCache ? false : true;
            }
            vk.callFunction({
                url: that.action,
                title: actionTitle,
                loading: actionAoading,
                data: {
                    goods_id: that.goodsId
                },
                success(data) {
                    that.updateGoodsInfo(data.goodsInfo);
                    // 更新缓存
                    goodsCache[that.goodsId] = data.goodsInfo;
                    that.$emit("update-goods", data.goodsInfo);
                },
                fail() {
                    that.updateValue(false);
                }
            });
        },
        updateValue(value) {
            let that = this;
            if (value) {
                that.$emit("open", true);
                that.$emit("input", true);
                that.$emit("update:modelValue", true);
            } else {
                that.$emit("input", false);
                that.$emit("close", "close");
                that.$emit("update:modelValue", false);
            }
        },
        // 更新商品信息(库存、名称、图片)
        updateGoodsInfo(goodsInfo) {
            let that = this;
            let {
                skuListName
            } = that;
            if (
                JSON.stringify(that.goodsInfo) === "{}" ||
                that.goodsInfo[that.goodsIdName] !== goodsInfo[that.goodsIdName]
            ) {
                that.goodsInfo = goodsInfo;
                that.initKey = true;
            } else {
                that.goodsInfo[skuListName] = goodsInfo[skuListName];
            }
            if (that.initKey) {
                that.initKey = false;
                that.init(that.isManyCom);
            }
            // 更新选中sku的库存信息
            let select_sku_info = that.getListItem(
                that.goodsInfo[skuListName],
                that.skuIdName,
                that.selectShop[that.skuIdName]
            );
            Object.assign(that.selectShop, select_sku_info);
            that.defaultSelectSku();
            that.complete = true;
        },
        async open() {
            let that = this;
            that.openTime = new Date().getTime();
            let findGoodsInfoRun = true;
            let skuListName = that.skuListName;
            // 先获取缓存中的商品信息
            let useCache = false;
            let goodsInfo = goodsCache[that.goodsId];
            if (goodsInfo && that.useCache) {
                useCache = true;
                that.updateGoodsInfo(goodsInfo);
            } else {
                that.complete = false;
            }
            if (that.customAction && typeof that.customAction === "function") {
                try {
                    goodsInfo = await that
                        .customAction({
                            useCache,
                            goodsId: that.goodsId,
                            goodsInfo,
                            close: function () {
                                setTimeout(function () {
                                    that.close();
                                }, 500);
                            }
                        })
                        .catch(err => {
                            setTimeout(function () {
                                that.close();
                            }, 500);
                        });
                } catch (err) {
                    let {
                        message = ""
                    } = err;
                    if (message.indexOf(".catch is not a function") > -1) {
                        that.$message.error("custom-action必须返回一个Promise")
                        setTimeout(function () {
                            that.close();
                        }, 500);
                        return false;
                    }
                }
                // 更新缓存
                goodsCache[that.goodsId] = goodsInfo;
                if (goodsInfo && typeof goodsInfo == "object" && JSON.stringify(goodsInfo) != "{}") {
                    findGoodsInfoRun = false;
                    that.updateGoodsInfo(goodsInfo);
                    that.updateValue(true);
                } else {
                    that.$message.error("未获取到商品信息")
                    that.$emit("input", false);
                    return false;
                }
            } else if (typeof that.localdata !== "undefined" && that.localdata !== null) {
                goodsInfo = that.localdata;
                if (goodsInfo && typeof goodsInfo == "object" && JSON.stringify(goodsInfo) != "{}") {
                    findGoodsInfoRun = false;
                    that.updateGoodsInfo(goodsInfo);
                    that.updateValue(true);
                } else {
                    that.$message.error("未获取到商品信息")
                    that.$emit("input", false);
                    return false;
                }
            } else {
                if (findGoodsInfoRun) that.findGoodsInfo({
                    useCache
                });
            }
        },
        // 监听 - 弹出层收起
        close(s) {
            let that = this;
            if (new Date().getTime() - that.openTime < 400) {
                return false;
            }
            if (s == "mask") {
                if (that.maskCloseAble !== false) {
                    that.$emit("input", false);
                    that.$emit("close", "mask");
                    that.$emit("update:modelValue", false);
                }
            } else {
                that.$emit("input", false);
                that.$emit("close", "close");
                that.$emit("update:modelValue", false);
            }
        },
        moveHandle() {
            //禁止父元素滑动
        },
        // sku按钮的点击事件
        skuClick(value, index1, index2) {
            let that = this;
            if (value.ishow) {
                if (that.selectArr[index1] != value.name) {
                    that.$set(that.selectArr, index1, value.name);
                    that.$set(that.subIndex, index1, index2);
                } else {
                    that.$set(that.selectArr, index1, "");
                    that.$set(that.subIndex, index1, -1);
                }
                that.checkInpath(index1);
                // 如果全部选完
                that.checkSelectShop();
            }
        },
        // 检测是否已经选完sku
        checkSelectShop() {
            let that = this;
            // 如果全部选完
            if (that.selectArr.every(item => item != "")) {
                that.selectShop = that.shopItemInfo[that.getArrayToSting(that.selectArr)];
                that.selectNum = that.minBuyNumCom;
                let stock = that.selectShop[that.stockName]
                if (that.selectNum > stock) {
                    // that.selectNum = stock;
                    that.isAddBtnDisabled = true;
                    that.addCartBtnText = '库存数量小于最低起卖数量'
                } else {
                    that.isAddBtnDisabled = false;
                    that.addCartBtnText = '加入购物车'
                }
                /* if (typeof stock !== "undefined" && that.selectNum > stock) {
                    console.log('22222222 选中的数量大于库存数量')
                    that.selectNum = stock;
                } */
                if (that.selectNum > that.maxBuyNum) {
                    that.selectNum = that.maxBuyNum;
                }
                if (that.selectNum < that.minBuyNum) {
                    that.selectNum = that.minBuyNum;
                }
                if (that.selectedInit) {
                    that.selectNum = that.minBuyNumCom;
                }
            } else {
                that.selectShop = {};
                that.initSwiper()
            }
        },
        // 检查路径
        checkInpath(clickIndex) {
            let that = this;
            let specListName = that.specListName;
            //console.time('筛选可选路径需要的时间是');
            //循环所有属性判断哪些属性可选
            //当前选中的兄弟节点和已选中属性不需要循环
            let specList = that.goodsInfo[specListName];
            for (let i = 0, len = specList.length; i < len; i++) {
                if (i == clickIndex) {
                    continue;
                }
                let len2 = specList[i].list.length;
                for (let j = 0; j < len2; j++) {
                    if (that.subIndex[i] != -1 && j == that.subIndex[i]) {
                        continue;
                    }
                    let choosed_copy = [...that.selectArr];
                    that.$set(choosed_copy, i, specList[i].list[j].name);
                    let choosed_copy2 = choosed_copy.filter(
                        item => item !== "" && typeof item !== "undefined"
                    );
                    if (that.shopItemInfo.hasOwnProperty(that.getArrayToSting(choosed_copy2))) {
                        specList[i].list[j].ishow = true;
                    } else {
                        specList[i].list[j].ishow = false;
                    }
                }
            }
            that.$set(that.goodsInfo, specListName, specList);
            // console.timeEnd('筛选可选路径需要的时间是');
        },
        // 计算sku里面规格形成路径
        checkItem() {
            let that = this;
            // console.time('计算有多小种可选路径需要的时间是');
            let {
                stockName
            } = that;
            let skuListName = that.skuListName;
            // 去除库存小于等于0的商品sku
            let originalSkuList = that.goodsInfo[skuListName];
            let skuList = [];
            let stockNum = 0;
            originalSkuList.map((skuItem, index) => {
                if (skuItem[stockName] > 0) {
                    skuList.push(skuItem);
                    stockNum += skuItem[stockName];
                }

            });
            if (stockNum <= 0) {
                that.outFoStock = true;
            }
            // 计算有多小种可选路径
            let result = skuList.reduce(
                (arrs, items) => {
                    return arrs.concat(
                        items[that.skuArrName].reduce(
                            (arr, item) => {
                                return arr.concat(
                                    arr.map(item2 => {
                                        // 利用对象属性的唯一性实现二维数组去重
                                        //console.log(1,that.shopItemInfo,that.getArrayToSting([...item2, item]),item2,item,items);
                                        if (!that.shopItemInfo.hasOwnProperty(that.getArrayToSting([...
                                            item2, item
                                        ]))) {
                                            that.shopItemInfo[that.getArrayToSting([...item2, item])] =
                                                items;
                                        }
                                        return [...item2, item];
                                    })
                                );
                            },
                            [
                                []
                            ]
                        )
                    );
                },
                [
                    []
                ]
            );
            // console.timeEnd('计算有多小种可选路径需要的时间是');
        },
        getArrayToSting(arr) {
            let str = "";
            arr.map((item, index) => {
                item = item.replace(/\./g, "。");
                if (index == 0) {
                    str += item;
                } else {
                    str += "," + item;
                }
            });
            return str;
        },
        // 检测sku选项是否已全部选完,且有库存
        checkSelectComplete(obj = {}) {
            let that = this;
            let clickTime = new Date().getTime();
            if (that.clickTime && clickTime - that.clickTime < 400) {
                return false;
            }
            that.clickTime = clickTime;
            let {
                selectShop,
                selectNum,
                stockText,
                stockName
            } = that;
            if (!selectShop || !selectShop[that.skuIdName]) {
                that.$message.error('请先选择对应规格')
                return false;
            }
            if (selectNum <= 0) {
                that.$message.err('购买数量必须>0')
                return false;
            }
            // 判断库存
            if (selectNum > selectShop[stockName]) {
                that.$message.err(stockText + "不足")
                return false;
            }
            if (typeof obj.success == "function") obj.success(selectShop);
        },
        // 加入购物车
        addCart() {
            let that = this;
            console.log('that.goodsInfo._id', that.goodsInfo._id)
            if (!localStorage.getItem('Client-Access-Token')) {
                that.$message.error('请先登录！');
                that.$router.push({
                    path: '/login',
                    // query: {
                    //     redirect: `/goods_detail?goods_id=${that.goodsInfo._id}`
                    // }
                })
                return;
            }
            that.checkSelectComplete({
                success: function (selectShop) {
                    selectShop.buy_num = that.selectNum;
                    console.log('加入购物车', selectShop)
                    that.$emit("addCartEv", selectShop);
                    // setTimeout(function() {
                    // 	that.init();
                    // }, 300);
                }
            });
        },
        // 立即购买
        buyNow() {
            let that = this;
            that.checkSelectComplete({
                success: function (selectShop) {
                    selectShop.buy_num = that.selectNum;
                    that.$emit("buy-now", selectShop);
                }
            });
        },
        // 弹窗
        toast(title, icon) {
            uni.showToast({
                title: title,
                icon: icon
            });
        },
        // 获取对象数组中的某一个item,根据指定的键值
        getListItem(list, key, value) {
            let that = this;
            let item;
            for (let i in list) {
                if (typeof value == "object") {
                    if (JSON.stringify(list[i][key]) === JSON.stringify(value)) {
                        item = list[i];
                        break;
                    }
                } else {
                    if (list[i][key] === value) {
                        item = list[i];
                        break;
                    }
                }
            }
            return item;
        },
        getListIndex(list, key, value) {
            let that = this;
            let index = -1;
            for (let i = 0; i < list.length; i++) {
                if (list[i][key] === value) {
                    index = i;
                    break;
                }
            }
            return index;
        },
        // 自动选择sku前提是只有一组sku,默认自动选择最前面的有库存的sku
        autoClickSku() {
            let that = this;
            let skuList = that.goodsInfo[that.skuListName];
            let specListArr = that.goodsInfo[that.specListName];
            if (specListArr.length == 1) {
                let specList = specListArr[0].list;
                for (let i = 0; i < specList.length; i++) {
                    let sku = that.getListItem(skuList, that.skuArrName, [specList[i].name]);
                    if (sku) {
                        that.skuClick(specList[i], 0, i);
                        break;
                    }
                }
            }
        },
        // 主题颜色
        themeColorFn(name) {
            let that = this;
            let {
                theme,
                themeColor
            } = that;
            let color = that[name] ? that[name] : themeColor[theme][name];
            return color;
        },
        defaultSelectSku() {
            let that = this;
            let {
                defaultSelect
            } = that;
            if (defaultSelect && defaultSelect.sku && defaultSelect.sku.length > 0) {
                that.selectSku(defaultSelect);
            }
        },

        selectSku(obj = {}) {
            let that = this;
            let {
                sku: skuArr,
                num: selectNum
            } = obj;
            let specListArr = that.goodsInfo[that.specListName];
            if (skuArr && specListArr.length === skuArr.length) {
                // 先清空
                let skuClickArr = [];
                let clickKey = true;
                for (let index = 0; index < skuArr.length; index++) {
                    let skuName = skuArr[index];
                    let specList = specListArr[index].list;
                    let index1 = index;
                    let index2 = that.getListIndex(specList, "name", skuName);
                    if (index2 == -1) {
                        clickKey = false;
                        break;
                    }
                    skuClickArr.push({
                        spec: specList[index2],
                        index1: index1,
                        index2: index2
                    });
                }
                if (clickKey) {
                    that.init(true);
                    skuClickArr.map(item => {
                        that.skuClick(item.spec, item.index1, item.index2);
                    });
                }
            }
            if (selectNum > 0) that.selectNum = selectNum;
        },
        priceFilter(n = 0) {
            let that = this;
            if (typeof n == "string") {
                n = parseFloat(n);
            }
            if (that.amountType === 0) {
                return n.toFixed(2);
            } else {
                return (n / 100).toFixed(2);
            }
        },
        pushGoodsCache(goodsInfo) {
            let that = this;
            let {
                goodsIdName
            } = that;
            goodsCache[goodsInfo[goodsIdName]] = goodsInfo;
        },
        // 用于阻止冒泡
        stop() { },
        // 图片预览
        previewImage() {
            let that = this;
            let {
                selectShop,
                goodsInfo,
                goodsThumbName
            } = that;
            let src = selectShop.image ? selectShop.image : goodsInfo[goodsThumbName];
            if (src) {
                uni.previewImage({
                    urls: [src]
                });
            }
        }
    },
    // 计算属性
    computed: {
        // 最大购买数量
        maxBuyNumCom() {
            let that = this;
            let max = that.maxBuyNum || 100000;
            let stockName = that.stockName;
            if (that.selectShop && typeof that.selectShop[stockName] !== "undefined") {
                // 最大购买量不能超过当前商品的库存
                if (max > that.selectShop[stockName]) {
                    max = that.selectShop[stockName];
                }
            }
            return max;
        },
        //最小购买数量
        minBuyNumCom() {
            let that = this;
            let min = that.minBuyNum || 1;
            let stockName = that.stockName;
            if (min < that.selectShop.minimum) {
                min = that.selectShop.minimum
            }
            return min;
        },
        // 是否是多规格
        isManyCom() {
            let that = this;
            let {
                goodsInfo,
                defaultSingleSkuName,
                specListName
            } = that;
            let isMany = true;
            if (
                goodsInfo[specListName] &&
                goodsInfo[specListName].length === 1 &&
                goodsInfo[specListName][0].list.length === 1 &&
                goodsInfo[specListName][0].name === defaultSingleSkuName
            ) {
                isMany = false;
            }
            return isMany;
        },
        // 默认价格区间计算
        priceCom() {
            let str = "";
            // let that = this;
            // let {
            //     selectShop = {}, goodsInfo = {}, skuListName, skuIdName
            // } = that;
            // if (selectShop[skuIdName]) {
            //     str = that.priceFilter(selectShop.price);
            // } else {
            //     let skuList = goodsInfo[skuListName];
            //     if (skuList && skuList.length > 0) {
            //         let valueArr = [];
            //         skuList.map((skuItem, index) => {
            //             valueArr.push(skuItem.price);
            //         });
            //         let min = that.priceFilter(Math.min(...valueArr));
            //         let max = that.priceFilter(Math.max(...valueArr));
            //         if (min === max) {
            //             str = min + "";
            //         } else {
            //             str = `${min} - ${max}`;
            //         }
            //     }
            // }
            return str;
        },
        // 库存显示
        stockCom() {
            let str = "";
            let that = this;
            let {
                selectShop = {}, goodsInfo = {}, skuListName, stockName
            } = that;
            if (selectShop[stockName]) {
                str = selectShop[stockName];
            } else {
                let skuList = goodsInfo[skuListName];
                if (skuList && skuList.length > 0) {
                    let valueArr = [];
                    skuList.map((skuItem, index) => {
                        valueArr.push(skuItem[stockName]);
                    });
                    let min = Math.min(...valueArr);
                    let max = Math.max(...valueArr);
                    if (min === max) {
                        str = min;
                    } else {
                        str = `${min} - ${max}`;
                    }
                }
            }
            return str;
        },

    },
};
</script>

<style lang='scss' scoped>
.goods-info-wrap {
    width: 100%;
    padding: 24px 12px 30px;
    box-sizing: border-box;

    .goods-img {
        width: 450px;
        height: 450px;
        flex-shrink: 0;
        margin-right: 24px;
        border-radius: 10px;
        overflow: hidden;
        background: #f7f9fa;
        .swiper-wrapper {
            width: 450px;
            height: 450px;
            background: #f7f9fa;
        }
        .swiper-img {
            width: 450px;
            height: 450px;
        }
    }

    .right-goods-info {
        p {
            font-size: 22px;
        }
        h4 {
            color: #ff5000;
            padding-top: 6px;
        }

        .goods-price-wrap {
            width: 426px;
            height: 98px;
            background: #30b30e;
            border-radius: 13px;
            margin-top: 20px;

            h2 {
                font-size: 20px;
                color: #ffffff;
                padding-left: 10px;
                padding-top: 10px;
            }

            .goods-price {
                width: 418px;
                height: 52px;
                align-items: center;
                background: #ffffff;
                border-radius: 8px;
                margin: 4px auto 0;
                padding: 0 7px;
                box-sizing: border-box;
                p {
                    font-size: 28px;
                    color: #ff5040;
                    margin-right: 10px;
                    font-family: "DIN-BOLD";
                    i {
                        font-size: 14px;
                    }
                }

                span {
                    min-width: 112px;
                    height: 29px;
                    background: #30b30e;
                    padding:0 10px;
                    box-sizing: border-box;
                    border-radius: 15px;
                    color: #fff;
                }
            }
        }

        .attr-name {
            width: 56px;
            height: 36px;
            display: flex;
            align-items: center;
            font-size: 14px;
            flex-shrink: 0;
            margin-right: 20px;
        }

        .attr-info-wrap {
            // margin-top: 25px;

            .attr-item {
                display: flex;
                margin-top: 24px;

                .attr {
                    display: flex;
                    flex-wrap: wrap;

                    .attr-btn {
                        min-width: 76px;
                        height: 36px;
                        padding: 0 10px;
                        box-sizing: border-box;
                        background: rgba(0, 0, 0, 0.06);
                        border: 1px solid transparent;
                        border-radius: 6px;
                        margin-right: 10px;
                        margin-bottom: 10px;
                        cursor: pointer;
                        &:last-of-type {
                            margin-right: 0;
                        }
                        &:hover {
                            background: rgba(0, 0, 0, 0.1);
                        }
                        &.actived {
                            background: #fff7f3;
                            border: 1px solid #ff5000;
                            color: #ff5000;
                        }
                        &.noactived {
                            color: #c8c9cc;
                            background: #f2f3f5;
                            border-color: #f2f3f5;
                        }
                    }
                }
            }
        }

        .goods-handle-wrap {
            align-items: center;
            margin-top: 32px;

            .add-cart {
                width: 289px;
                height: 53px;
                background: #30b30e;
                border-radius: 27px;
                color: #fff;
                font-size: 16px;
                // margin-right: 40px;
                font-weight: bold;
                cursor: pointer;
            }
            .line {
                width: 1px;
                height: 18px;
                background: #c2c2c2;
                margin: 0 30px 0 16px;
            }
            .add-cart-disabled {
                color: #c3c3c3;
                background: #f6f6f6;
                cursor: not-allowed;
            }

            .collect {
                font-size: 14px;
                color: #8f8f8f;
                .check {
                    color: #ff5000;
                }
                p {
                    font-size: 14px;
                    margin-left: 4px;
                }
            }
        }
        .producer-wrap {
            margin-bottom: 16px;
            margin-top: 8px;
            .producer {
                font-size: 14px;
                line-height: 36px;
            }
        }
    }
}
.stock {
    color: #8d9ba8;
    font-size: 14px !important;
    line-height: 38px;
    margin-left: 10px;
    font-family: PingFangSC-Regular;
}
.unit{
    color: #8f8f8f;
}
</style>